package cn.reinforce.util.http.geetest;

import cn.reinforce.util.http.exception.NetworkException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 极验验证的二次验证
 * @author 幻幻Fate
 * @date 2018-02-25
 * @since 1.0.0
 */
public class GeetestUtil {

    private static final Logger LOG = LoggerFactory.getLogger(GeetestUtil.class.getName());

    private GeetestUtil() {
        super();
    }

    public static int validate(String captchaId, String privateKey, HttpServletRequest request){

        GeetestLib gtLib = new GeetestLib(captchaId, privateKey);

        String challenge = request.getParameter(GeetestLib.GEETEST_CHALLENGE);
        String validate = request.getParameter(GeetestLib.GEETEST_VALIDATE);
        String seccode = request.getParameter(GeetestLib.GEETEST_SECCODE);

        //从session中获取gt-server状态
        Integer status = (Integer) request.getSession().getAttribute(GeetestLib.GEETEST_SERVER_STATUS_SESSION_KEY);
        String userId = (String) request.getSession().getAttribute("userId");
        // session必须取出值，若取不出值，直接当做异常退出
        if(status == null){
            throw new NetworkException("session取key发生异常");
        }

        GeetestLibResult result = null;
        if (status == 1) {
            /*
            自定义参数,可选择添加
                user_id 客户端用户的唯一标识，确定用户的唯一性；作用于提供进阶数据分析服务，可在register和validate接口传入，不传入也不影响验证服务的使用；若担心用户信息风险，可作预处理(如哈希处理)再提供到极验
                client_type 客户端类型，web：电脑上的浏览器；h5：手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生sdk植入app应用的方式；unknown：未知
                ip_address 客户端请求sdk服务器的ip地址
            */
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("user_id", userId);
            paramMap.put("client_type", "web");
            paramMap.put("ip_address", "127.0.0.1");
            result = gtLib.successValidate(challenge, validate, seccode, paramMap);
        } else {
            result = gtLib.failValidate(challenge, validate, seccode);
        }

        if (result.getStatus() == 1) {
            System.out.println(result);
        } else {
            LOG.info("failback:use your own server captcha validate");
        }
        return result.getStatus();
    }
}
